<template>
  <div class="form">
    <el-form label-width="100px" @submit.native.prevent="add">
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <vue-editor v-model="form.banner"></vue-editor>
      </el-form-item>
      <el-form-item label="分类">
        <el-checkbox-group v-model="form.checkList">
          <el-checkbox label="Vue"></el-checkbox>
          <el-checkbox label="React"></el-checkbox>
          <el-checkbox label="Angular"></el-checkbox>
          <el-checkbox label="Node"></el-checkbox>
          <el-checkbox label="数据库"></el-checkbox>
          <el-checkbox label="Webpack"></el-checkbox>
          <el-checkbox label="Ajax"></el-checkbox>
          <el-checkbox label="jQuery"></el-checkbox>
          <el-checkbox label="JavaScript"></el-checkbox>
          <el-checkbox label="Bootstrap"></el-checkbox>
          <el-checkbox label="HTML5"></el-checkbox>
          <el-checkbox label="Css"></el-checkbox>
          <el-checkbox label="微信开发"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button v-if="this.id" type="primary" size="medium" @click="blogChange">提交</el-button>
        <el-button v-else type="primary" size="medium" native-type="add">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//富文本编辑器
import { VueEditor } from "vue2-editor"
export default {
  props: {
    id: {}
  },
  data() {
    return {
      form: {
        checkList: []
      }
    }
  },
  methods: {
    //添加博客
    async add() {
      if(this.form.title && this.form.banner && this.form.checkList.length > 0) {
        const res = await this.$http.post('/writing', this.form)
        if(res.status === 200) {
          this.$message({
            type: "success",
            message: '添加成功！'
          })
        this.$router.push('/read')//跳转阅读页
        } else {
          this.$message.error('添加失败！')
        }
      } else {
        this.$message({
          type: "warning",
          message: '请输入标题，内容或选择技术类型！'
        })
      }
    },
    //加载需要修改的博客的数据
    async fetch(id) {
      const res = await this.$http.get('/read/'+id)
      this.form = res.data
    },
    //修改博客
    async blogChange() {
      if(this.form.title && this.form.banner && this.form.checkList.length > 0) {
        const res = await this.$http.put(`/put/${this.id}`, this.form)
        if (res.status === 200) {
          this.$message({
            type: "success",
            message: '修改成功！'
          })
          this.$router.push('/read')
        }
      } else {
        this.$message({
          type: "warning",
          message: '请输入标题，内容或选择技术类型！'
        })
      }
    }
  },
  created() {
    this.id && this.fetch(this.id)
  },
  components: {
    VueEditor
  }
}
</script>

<style lang="scss">
.form {
  width: 60%;
  margin: 20px auto;
}
</style>

